<template>
  <AppPage fullViewport>
    <div class="login-form">
      <div>
        <div class="login-header">
          <h1>{{ appStore.name }}</h1>
        </div>
        <FormMain
          ref="formMain"
          :list="list"
          :data="data"
          labelPosition="top"
          size="large"
        >
          <template #account="scope">
            <ElInput v-bind="scope" />
          </template>
          <template #pwd="scope">
            <ElInput v-bind="scope" />
          </template>
          <template #remember="scope">
            <ElCheckbox v-bind="scope">记住密码</ElCheckbox>
          </template>
        </FormMain>
        <div class="login-btnGroup">
          <ElButton type="primary" class="login-btn" @click="onClick"
            >登录</ElButton
          >

          <!-- <ElButton text type="primary" @click="goToRegisterPage"
            >注册</ElButton
          > -->
        </div>
      </div>
    </div>
  </AppPage>
</template>
<script setup lang="ts">
import type {
  FormMainInstance,
  FormItemConfigList,
  FormModel,
} from "@/components/form";
import {
  generateFormData,
  stringifyFormData,
  FormVerifyImage,
} from "@/components/form";
import { useAppStore, useUserStore } from "@/store";
import { ElMessage } from "element-plus";
import type { AccountLoginParams } from "@/api";
import { getVerifyImage } from "@/api";
import { loginPath, homePath } from "@/router";
import { useState } from "@/hooks";

const appStore = useAppStore();

const userStore = useUserStore();

const router = useRouter();

const route = useRoute();

const from = computed(
  () => decodeURIComponent((route.query.from as string) || "") || homePath,
);

/** 登录表单hook */
const cacheHook = useState(
  (): Pick<AccountLoginParams, "account" | "pwd"> & {
    remember: boolean;
  } => {
    return {
      account: "",
      pwd: "",
      remember: false,
    };
  },
  {
    moduleKey: "LOGIN_FORM",
    debug: false,
    cache: true,
  },
);

const list: FormItemConfigList<
  AccountLoginParams & {
    remember: boolean;
  },
  {
    remember: never;
  }
> = [
  {
    key: "account",
    label: "账号",
    init: cacheHook.state.account,
    rules: [{ required: true, message: "请输入账号", trigger: "blur" }],
    extra: {
      isInput: true,
    },
  },
  {
    key: "pwd",
    label: "密码",
    init: cacheHook.state.pwd,
    props: {
      type: "password",
      showPassword: true,
    },
    rules: [{ required: true, message: "请输入密码", trigger: "blur" }],
    extra: {
      isInput: true,
    },
  },
  {
    key: "verify",
    label: "验证码",
    init: "",
    rules: [
      {
        required: true,
        trigger: "blur",
        message: "请输入验证码",
      },
    ],
    render: FormVerifyImage,
    extra: {
      isInput: true,
    },
    props: {
      api: () => getVerifyImage(),
    },
  },
  {
    key: "remember",
    label: "",
    init: cacheHook.state.remember,
    stringify: () => undefined,
  },
];

const data = ref<FormModel<typeof list>>(generateFormData(list));

const formMain = ref<FormMainInstance>();

const afterLogin = () => {
  if (new URL(from.value, window.location.origin).pathname === loginPath) {
    router.replace(homePath);
  } else {
    router.replace(from.value);
  }
};

const onClick = () => {
  formMain.value?.validate().then(() => {
    userStore.login(stringifyFormData(data.value, list)).then(() => {
      if (data.value.remember) {
        cacheHook.updateState({
          account: data.value.account,
          pwd: data.value.pwd,
          remember: data.value.remember,
        });
      } else {
        cacheHook.resetState();
      }
      ElMessage.success("登录成功");
    });
  });
};

// const goToRegisterPage = () => {
//   router.replace(registerPath);
// };

onMounted(() => {
  data.value = generateFormData(list);
});

// 保证及时登录了还来此页面，直接跳转回去
// 需要保证跳转来之前清除登录状态，上一个页面需要完成，
// 如果是接口报未登录会自动清除登录状态并跳转
watch(
  () => userStore.isLogin,
  (n) => {
    if (n) {
      afterLogin();
    }
  },
  {
    immediate: true,
  },
);
</script>
<style lang="less" scoped>
.login {
  &-header {
    text-align: center;
    padding-bottom: 100px;
  }
  &-form {
    width: 300px;
    height: 100vh;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &-btnGroup {
    display: flex;
    justify-content: center;
    width: 100%;
    .login-btn {
      width: 100%;
    }
  }
}
</style>
